#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <cstdio>

#include "message.pb.h"

int main(int argc, char *argv[])
{
    struct sockaddr_un sun;
    int sock;
    char *buf;

    if (argc != 2) {
        printf("Usage: %s <pid>\n", argv[0]);
        exit(0);
    }

    memset(&sun, 0, sizeof(sun));
    sun.sun_family = AF_UNIX;
    snprintf(sun.sun_path, sizeof(sun.sun_path), "/tmp/cvmfs_broker-%s",
            argv[1]);

    sock = socket(AF_UNIX, SOCK_STREAM, 0);
    if (sock < 0) {
        perror("socket");
        exit(1);
    }
    if (connect(sock, (sockaddr *)&sun, sizeof(sun)) != 0) {
        perror("connect");
        exit(1);
    }

    printf("connected!\n");
    cvmfs::P2BMessage msg;
    msg.set_recipient("somebody");
    msg.set_subject("REPLICA");
    msg.set_body("Hello world!");

    int size = msg.ByteSize();
    int nsize = htonl(size);
    buf = (char *)malloc(size + sizeof(int));
    if (buf == NULL) {
        printf("malloc failed\n");
        return 1;
    }
    printf("copying %d bytes\n", sizeof(nsize));
    memcpy(buf, &nsize, sizeof(nsize));
    printf("serializing message...\n");
    msg.SerializeToArray(buf + sizeof(size), size);
    printf("sending data (%d bytes)...\n", size + sizeof(int));
    if (send(sock, buf, size + sizeof(int), 0) <= 0) {
        printf("here!\n");
        perror("send");
    }
    printf("send %d bytes ok\n", size);

    close(sock);

    return 0;
}

